<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      #div1 {
        width: 100px;
        height: 100px;
        background-color: chartreuse;
        position: absolute;
        right: 0;
      }
    </style>
    <script>
      window.onload = function () {
        var oDiv = document.getElementById("div1");
        var scollTop =
          document.documentElement.scrollTop || document.body.scrollTop;
        var windowHeigh =
          document.documentElement.clientHeight || document.body.clientHeight;
        var iH = parseInt(scollTop + (windowHeigh - oDiv.offsetHeight) / 2);
        // startMove(iH);
        window.onscroll = function () {
          var scollTop =
            document.documentElement.scrollTop || document.body.scrollTop;
          var windowHeigh =
            document.documentElement.clientHeight || document.body.clientHeight;
          var iH = parseInt(scollTop + (windowHeigh - oDiv.offsetHeight) / 2);
          startMove(iH);
        };
        window.onresize = function () {
          var scollTop =
            document.documentElement.scrollTop || document.body.scrollTop;
          var windowHeigh =
            document.documentElement.clientHeight || document.body.clientHeight;
          var iH = parseInt(scollTop + (windowHeigh - oDiv.offsetHeight) / 2);
          startMove(iH);
        };
        var timer = null;
        function startMove(iTarget) {
          clearTimeout(timer);
          timer = setInterval(function () {
            var speed = (iTarget - oDiv.offsetTop) / 8;
            speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
            oDiv.style.top = oDiv.offsetTop + speed + "px";
            if (oDiv.offsetTop === iTarget) {
              clearTimeout(timer);
            }
          }, 30);
        }
      };
    </script>
  </head>
  <body style="height: 3000px;">
    <div id="div1"></div>
  </body>
</html>
